//===============================================================================================
//
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.
//
//===============================================================================================

using System;
using System.Configuration;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using MyWebPagesStarterKit.Controls;
using MyWebPagesStarterKit;
using System.Collections.Generic;
using System.Xml;
using System.Web.Security;

public partial class _Default : PageBaseClass
{
    private WebPage _page;
   

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (User.IsInRole(RoleNames.Administrators.ToString())) // only admin can create new sections
            {
               

				List<ISection> sectionList = new List<ISection>();
				foreach (Type t in _page.GetType().Assembly.GetTypes())
				{
					//find all classes that implement ISection and are not abstract
					if (t.IsClass && (t.GetInterface("ISection") != null) && (!t.IsAbstract))
					{
						//create a empty section-object for each found type
						ISection section = t.GetConstructor(new Type[] { }).Invoke(new object[] { }) as ISection;
						sectionList.Add(section);						
					}
				}

				//sort the list alphabetically by their localized names
				sectionList.Sort(new Comparison<ISection>(sectionComparer));

				foreach (ISection section in sectionList)
				{
					cmbSections.Items.Add(new ListItem(section.GetLocalizedSectionName(), section.GetType().AssemblyQualifiedName));
				}

                LoadTemplateList();
            }
            else
            {
                pageexplorer.Visible = false;
            }
        }

        if (Page.User.IsInRole(MyWebPagesStarterKit.RoleNames.Administrators.ToString()))
        {
            chkPageStatus.Checked = _page.Visible;
            chkHidden.Checked = _page.Hidden;

            if (_page.PageId == _website.HomepageId)
            {
                chkPageStatus.Enabled = false;
                chkHidden.Enabled = false;
            }

        }
    }

    protected void LogoutUser(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Response.Redirect("~/");
    }

    /// <summary>
    /// Loads all templates or this webpage
    /// </summary>
    private void LoadTemplateList()
    {
        WebPage page = WebPage.Current;
        XmlDocument xml = new XmlDocument();
        xml.Load(Server.MapPath("~/web.config"));
        XmlNode root = xml.SelectSingleNode("configuration/templates/themes");

        string theme = WebSite.GetInstance().Theme;

        if (root.HasChildNodes)
        {
            foreach (XmlNode node in root.ChildNodes)
            {
                if (page.TemplateName.Equals(node.Attributes["template"].Value) && Page.Theme.Equals(node.Attributes["name"].Value))
                {
                    string[] columns = node.Attributes["columns"].Value.Split(new char[] { ',' });

                    foreach (string column in columns)
                    {
                        string name = string.Format("pos_{0}_Title", column.ToUpper());
                        cmbPositions.Items.Add(new ListItem(Resources.StringsRes.ResourceManager.GetString(name), column));
                    }

                    break;
                }
            }
        }
    }



	private static int sectionComparer(ISection a, ISection b)
	{
        return a.GetLocalizedSectionName().CompareTo(b.GetLocalizedSectionName());
	}



    protected void btnNewSection_Click(object sender, EventArgs e)
    {
        ISection newSection = (ISection)Activator.CreateInstance(Type.GetType(cmbSections.SelectedValue));
        Position pos = Position.UNKNOWN;

        switch (cmbPositions.SelectedValue)
        {
            case "TOP":
                pos = Position.TOP;
                break;
            case "LEFT":
                pos = Position.LEFT;
                break;
            case "CENTER":
                pos = Position.CENTER;
                break;
            case "RIGHT":
                pos = Position.RIGHT;
                break;
            case "BOTTOM":
                pos = Position.BOTTOM;
                break;
        }

        newSection.Position = pos;
        newSection.SaveData();

        _page.AddSection(newSection.SectionId);
        _page.SaveData();

        RolesManagement.GetInstance().AddRole(newSection, "UnAuthenticated", Rule.VIEW);
        RolesManagement.GetInstance().AddRole(newSection, "Users", Rule.VIEW);
        RolesManagement.GetInstance().AddRole(newSection, "PowerUsers", Rule.EDIT);

        Response.Redirect(Request.RawUrl);
    }

    protected void PageStatus(object sender, EventArgs e)
    {
        if (_page.PageId != _website.HomepageId)
        {
            if (chkPageStatus.Checked)
                _page.Visible = false;
            else
                _page.Visible = true;

            chkPageStatus.Checked = _page.Visible;
            _page.SaveData();

            SitemapEditor editor = new SitemapEditor();
            editor.UpdatePage(_page, null);
            editor.Save();
        }
    }

    protected void HiddenStatus(object sender, EventArgs e)
    {
        if (_page.PageId != _website.HomepageId)
        {
            if (chkHidden.Checked)
                _page.Hidden = false;
            else
                _page.Hidden = true;

            chkHidden.Checked = _page.Hidden;
            _page.SaveData();

            SitemapEditor editor = new SitemapEditor();
            editor.UpdatePage(_page, null);
            editor.Save();
        }
    }


    protected void ViewAdminPage(object sender, EventArgs e)
    {
        Response.Redirect(string.Format("/Administration/Navigation.aspx?sel={0}" , WebPage.Current.PageId));
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        if (Request.QueryString["pg"] != null)
        {
            _page = WebPage.Current;

            if ((_page.AllowAnonymousAccess == false) && (User.Identity.IsAuthenticated == false))
                _page = new WebPage(_website.HomepageId);

            if (_page.Visible == false)
            {
                if (!((User.Identity.IsAuthenticated) && ((User.IsInRole(RoleNames.Administrators.ToString())) || User.IsInRole(RoleNames.PowerUsers.ToString()))))
                    _page = new WebPage(_website.HomepageId);
            }
        }
        else
        {
            Context.RewritePath(string.Format("{0}?pg={1}", Request.Path, _website.HomepageId));
            _page = new WebPage(_website.HomepageId);
        }

        Session["Homepage"] = (_page.PageId == _website.HomepageId);


        //Page title
        if (_page.Title.Trim() != string.Empty)
            Title = _page.Title;
        else
            Title = _website.WebSiteTitle;

        //Description
        if (_page.Description.Trim() != string.Empty)
            Header.Controls.Add(WebPage.generateMeta("description", _page.Description));
        else if (_website.Description.Trim() != string.Empty)
            Header.Controls.Add(WebPage.generateMeta("description", _website.WebSiteTitle));

        //Keywords
        if (_page.Keywords.Trim() != string.Empty)
            Header.Controls.Add(WebPage.generateMeta("keywords", _page.Keywords));
        else if (_website.Keywords.Trim() != string.Empty)
            Header.Controls.Add(WebPage.generateMeta("keywords", _website.Keywords));

        Header.Controls.Add(WebPage.generateMeta("generator", "Enterprisesoft development " + ConfigurationManager.AppSettings["Version"]));

        //Google sitemap
        if (!string.IsNullOrEmpty(_website.GoogleSiteMapKey))
            Header.Controls.Add(WebPage.generateMeta("google-site-verification", _website.GoogleSiteMapKey));

        //Google Analytics
        if (!string.IsNullOrEmpty(_website.GoogleAnalyticsKey))
        {
            string script = ""
               + "<script type=\"text/javascript\">\n"
               + "     var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");\n"
               + "     document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E \"));\n"
               + "</script>\n"
               + "<script type=\"text/javascript\">\n"
               + "var pageTracker = _gat._getTracker(\"" + _website.GoogleAnalyticsKey + "\");\n"
               + "pageTracker._trackPageview();\n"
               + "</script>\n";

               ClientScript.RegisterStartupScript(this.GetType(),"GoogleUACCT", script);
        }
    }
}
